package com.polaris.live.widget.marqueen

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import androidx.lifecycle.LifecycleCoroutineScope
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.manager.CoroutineScopeManager
import com.polaris.live.databinding.WidgetRankBannerBinding
import com.polaris.live.resp.back_resp.HonorRankResp
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.playAsync
import com.polaris.live.utils.route.RouterUtils
import kotlinx.coroutines.launch
import org.libpag.PAGImage
import org.libpag.PAGScaleMode

/**
 * 派对页Banner数据
 *
 * @author Created by 天晴 on 2024/12/4/028 15:33
 */
class RankBannerView(context: Context, attributeSet: AttributeSet?) : LinearLayout(context, attributeSet) {

    private val mBinding = WidgetRankBannerBinding.inflate(LayoutInflater.from(context), this)
    private var isLoad = false
    private var headOne = ""
    private var headTwo = ""
    private var headThree = ""
    fun setData(lifecycleScope: LifecycleCoroutineScope, data: HonorRankResp) {
        val nowHeadOne = data.ranks.getOrNull(0)?.user?.avatar ?: ""
        val nowHeadTwo = data.ranks.getOrNull(1)?.user?.avatar ?: ""
        val nowHeadThree = data.ranks.getOrNull(2)?.user?.avatar ?: ""
        if (isLoad && headOne == nowHeadOne && headTwo == nowHeadTwo && headThree == nowHeadThree) { //数据一样且加载了，不再加载
            return
        }
        headOne = nowHeadOne
        headTwo = nowHeadTwo
        headThree = nowHeadThree
        mBinding.pagImage.playAsync(lifecycleScope, data.banner) {
            mBinding.ivLoading.visibility = View.GONE
            setRepeatCount(-1)
            setScaleMode(PAGScaleMode.Zoom)
            try {
                lifecycleScope.launch(CoroutineScopeManager.ioDispatcher) {
                    val head1 = ImageUtils.loadNetImageBitmapNoTransform(context, nowHeadOne)
                    val pagImage1 = PAGImage.FromBitmap(head1)
                    it.replaceImage(1, pagImage1)

                    val head2 = ImageUtils.loadNetImageBitmapNoTransform(context, nowHeadTwo)
                    val pagImage2 = PAGImage.FromBitmap(head2)
                    it.replaceImage(2, pagImage2)

                    val head3 = ImageUtils.loadNetImageBitmapNoTransform(context, nowHeadThree)
                    val pagImage3 = PAGImage.FromBitmap(head3)
                    it.replaceImage(3, pagImage3)
                }
            } catch (_: Exception) {
            }
            isLoad = true
        }

        mBinding.root.setOnSingleClickListener {
            data.router?.let { RouterUtils.routerGoto(it) }
        }
    }

}